package com.graduate.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.graduate.common.R;
import com.graduate.dto.GoodsDto;
import com.graduate.entity.*;
import com.graduate.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

//商品管理
@RestController
@RequestMapping("/goods")
@Slf4j
public class GoodsController {
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private GoodsNoteService goodsNoteService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private SetmealGoodsService setmealGoodsService;
    @Autowired
    private SetMealService setMealService;

    //新增商品
    @PostMapping
    public R<String> save(@RequestBody GoodsDto goodsDto){
        log.info(goodsDto.toString());
        goodsService.saveWithNote(goodsDto);
        return R.success("新增商品成功");
    }

    //商品信息分页查询
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
        //构造分页构造器
        Page<Goods> pageInfo = new Page<>(page,pageSize);
        Page<GoodsDto> goodsDtoPage = new Page<>();

        //条件构造器
        LambdaQueryWrapper<Goods> queryWrapper = new LambdaQueryWrapper<>();
        //添加过滤条件
        queryWrapper.like(name != null,Goods::getName,name);
        //添加排序条件
        queryWrapper.orderByDesc(Goods::getUpdateTime);
        //执行分页查询
        goodsService.page(pageInfo,queryWrapper);
        //对象拷贝
        BeanUtils.copyProperties(pageInfo,goodsDtoPage,"records");

        List<Goods> records = pageInfo.getRecords();
        List<GoodsDto> list =records.stream().map((item) -> {
            GoodsDto goodsDto = new GoodsDto();
            BeanUtils.copyProperties(item,goodsDto);
            //分类id
            Long categoryId = item.getCategoryId();
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);
            if (category != null){
                String categoryName = category.getName();
                goodsDto.setCategoryName(categoryName);
            }
            return goodsDto;
        }).collect(Collectors.toList());

        goodsDtoPage.setRecords(list);

        return R.success(goodsDtoPage);
    }

    //根据id查询商品信息和对应的note
    @GetMapping("/{id}")
    public R<GoodsDto> get(@PathVariable Long id){
        GoodsDto goodsDto = goodsService.getByIdWithNote(id);
        return R.success(goodsDto);
    }

    //修改商品
    @PutMapping
    public R<String> update(@RequestBody GoodsDto goodsDto){
        log.info(goodsDto.toString());
        goodsService.updateWithNote(goodsDto);
        return R.success("修改商品成功");
    }

    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids){
        //根据商品id在stemeal_goods表中查出哪些套餐包含该商品
        LambdaQueryWrapper<SetmealGoods> setmealDishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealDishLambdaQueryWrapper.in(SetmealGoods::getGoodsId,ids);
        List<SetmealGoods> SetmealDishList = setmealGoodsService.list(setmealDishLambdaQueryWrapper);
        //如果商品没有关联套餐，直接删除
        if (SetmealDishList.size() == 0){
            //这个deleteByIds中已经做了商品起售不能删除的判断力
            goodsService.deleteByIds(ids);
            LambdaQueryWrapper<GoodsNote> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(GoodsNote::getGoodsId,ids);
            goodsNoteService.remove(queryWrapper);
            return R.success("商品删除成功");
        }

        //如果商品有关联套餐，并且该套餐正在售卖，那么不能删除
        //得到与删除商品关联的套餐id
        ArrayList<Long> Setmeal_idList = new ArrayList<>();
        for (SetmealGoods setmealGoods : SetmealDishList) {
            Long setmealId = setmealGoods.getSetmealId();
            Setmeal_idList.add(setmealId);
        }
        //查询出与删除商品相关联的套餐
        LambdaQueryWrapper<SetMeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.in(SetMeal::getId,Setmeal_idList);
        List<SetMeal> setmealList = setMealService.list(setmealLambdaQueryWrapper);
        //对拿到的所有套餐进行遍历，然后拿到套餐的售卖状态，如果有套餐正在售卖那么删除失败
        for (SetMeal setmeal : setmealList) {
            Integer status = setmeal.getStatus();
            if (status == 1){
                return R.error("删除的商品中有关联在售套餐,删除失败！");
            }
        }
        //要删除的商关联的套餐没有在售，可以删除
        //这下面的代码并不一定会执行,因为如果前面的for循环中出现status == 1,那么下面的代码就不会再执行
        goodsService.deleteByIds(ids);
        LambdaQueryWrapper<GoodsNote> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(GoodsNote::getGoodsId,ids);
        goodsNoteService.remove(queryWrapper);
        return R.success("商品删除成功");
    }


    //批量起售、停售
    @PostMapping("/status/{status}")
    public R<String> updateMulStatus(@PathVariable Integer status, Long[] ids){
        List<Long> list = Arrays.asList(ids);
        //list.forEach(System.out::println);

        //构造条件构造器
        LambdaUpdateWrapper<Goods> updateWrapper = new LambdaUpdateWrapper<>();
        //添加过滤条件
        updateWrapper.set(Goods::getStatus,status).in(Goods::getId,list);
        goodsService.update(updateWrapper);

        return R.success("商品信息修改成功");
    }

    //根据条件查询对应的商品数据
//    @GetMapping("/list")
//    public R<List<Goods>> list(Goods goods){
//        //构造查询条件
//        LambdaQueryWrapper<Goods> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(goods.getCategoryId() != null,Goods::getCategoryId,goods.getCategoryId());
//        //查询状态为1起售状态商品
//        queryWrapper.eq(Goods::getStatus,1);
//        //添加排序条件
//        queryWrapper.orderByAsc(Goods::getSort).orderByDesc(Goods::getUpdateTime);
//        List<Goods> list = goodsService.list(queryWrapper);
//        return R.success(list);
//    }
    @GetMapping("/list")
    public R<List<GoodsDto>> list(Goods goods){
        //构造查询条件
        LambdaQueryWrapper<Goods> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(goods.getCategoryId() != null,Goods::getCategoryId,goods.getCategoryId());
        //查询状态为1起售状态商品
        queryWrapper.eq(Goods::getStatus,1);
        //添加排序条件
        queryWrapper.orderByAsc(Goods::getSort).orderByDesc(Goods::getUpdateTime);
        List<Goods> list = goodsService.list(queryWrapper);


        List<GoodsDto> goodsDtoList =list.stream().map((item) -> {
            GoodsDto goodsDto = new GoodsDto();
            BeanUtils.copyProperties(item,goodsDto);
            //分类id
            Long categoryId = item.getCategoryId();
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);
            if (category != null){
                String categoryName = category.getName();
                goodsDto.setCategoryName(categoryName);
            }
            //当前商品的id
            Long goodsId = item.getId();
            LambdaQueryWrapper<GoodsNote> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(GoodsNote::getGoodsId,goodsId);
            List<GoodsNote> goodsNoteList = goodsNoteService.list(lambdaQueryWrapper);
            goodsDto.setFlavors(goodsNoteList);
            return goodsDto;
        }).collect(Collectors.toList());


        return R.success(goodsDtoList);
    }


}
